<template>
  <div class="publish-content">
    <baseTable
      :page.sync="page"
      :cols="tableCols"
      :data="tableData"
      :hasCheck="true"
    >
      <template #head>
        <div class="head">
          <div class="search">
            <el-cascader
              v-model="areaInfo"
              :options="cityList"
              :props="casxaderProps"
              placeholder="体检城市"
              class="area-cascader"
              :show-all-levels="false"
              @change="handleChangeArea"
              clearable
            ></el-cascader>
            <el-select
              class="bar-left-select ml-10"
              v-model="params.year"
              placeholder="体检年份"
              clearable
            >
              <el-option
                v-for="item in yearOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
            <el-input
              placeholder="请输入任务名称、体系名称"
              v-model="params.keywords"
            >
              <i
                slot="suffix"
                class="el-input__icon el-icon-search cursor-pointer"
                @click="getList"
              ></i>
            </el-input>
          </div>
          <div></div>
        </div>
      </template>
      <template #cols>
        <el-table-column label="报告名称" align="center">
          <template #default="scope">
            <div class="file-list">
              <div
                class="file-list-item"
                :key="index"
                v-for="(file, index) in scope.row.indexSubmitAttachRelList"
              >
                <span
                  @click="handleDownloadFile(file.attachmentId, file.fileName)"
                  style="color: rgb(56, 148, 255); cursor: pointer"
                  >{{ file.fileName }}</span
                >
                <i
                  @click.stop="handleRemoveFile(file.pkid)"
                  class="el-icon el-icon-close"
                  style="cursor: pointer"
                ></i>
              </div>
            </div>
          </template>
        </el-table-column>
        <!-- <el-table-column label="发布进度" align="center">
          <template slot-scope="scope">
            <div class="flex items-center">
              <div class="progress-bg flex-1 mr-10">
                <div
                  class="progress"
                  :style="{
                    width: `${scope.row.indexDataProgressVo.progress}%`,
                  }"
                ></div>
              </div>
              {{ scope.row.indexDataProgressVo.isRealease }}/
              {{ scope.row.indexDataTotal }}
            </div>
          </template>
        </el-table-column> -->
        <el-table-column label="操作" width="200" align="center">
          <template slot-scope="scope">
            <el-button
              v-if="currentUser?.hasPermission(PERMISSIONS.报告上传上传)"
              type="text"
              @click.stop="uploadReport(scope.row.pkid)"
              >{{
                currentUser?.getButtonName(PERMISSIONS.报告上传上传)
              }}</el-button
            >

            <!-- <el-link
              slot="reference"
              class="mr-10"
              type="primary"
              @click="goEdit(scope.row.pkid)"
              :underline="false"
              >详情</el-link
            > -->
            <!-- <el-link slot="reference" class="mr-10" type="primary" @click="goEdit(scope.row.pkid, true)" :underline="false">编辑</el-link> -->
            <!-- <el-popconfirm
                title="确定发布已填写的指标？"
                @confirm="handleRelease(scope.row.pkid)"
              >
                <el-link slot="reference" class="mr-10" type="primary" :underline="false">发布</el-link>
              </el-popconfirm> -->
          </template>
        </el-table-column>
      </template>
    </baseTable>
  </div>
</template>

<script>
import baseTable from '@c/base-table'
import {
  queryQuotaList,
  getAreaList,
  getYearList,
  releaseIndex,
} from '@/api/indicator-manage'
import { downloadFile, queryArea, uploadFile } from '@api/question'
import { deleteSubmit, querySubmit, uploadSubmit } from '@api/city-index'
import { Message } from 'element-ui'
import axios from 'axios'
import { mapGetters } from 'vuex'
import { PERMISSIONS } from '@/common/user'
export default {
  name: 'dataRelaes',
  components: { baseTable },
  computed: {
    ...mapGetters(['currentUser']),
  },
  data() {
    return {
      PERMISSIONS,
      page: {
        pageIndex: 1,
        pageSize: 10,
        total: 0,
      },
      params: {
        areaId: null,
        districtId: null,
        year: null,
        keywords: null,
        status: 1,
      },
      tableData: [],
      tableCols: [
        {
          prop: 'regionName',
          label: '体检城市',
        },
        {
          prop: 'taskName',
          label: '任务名称',
        },
        {
          prop: 'indexName',
          label: '指标体系名称',
        },
        {
          prop: 'year',
          label: '体检年份',
        },
        {
          prop: 'completeTime',
          label: '完成时限',
        },
        {
          prop: 'updateTime',
          label: '更新时间',
        },
      ],
      cityList: [],
      casxaderProps: {
        value: 'areaCode',
        label: 'areaName',
        checkStrictly: true,
        children: 'children',
      },
      areaInfo: [],
      yearOptions: [
        {
          value: '2021',
          label: '2021年',
        },
        {
          value: '2022',
          label: '2022年',
        },
        {
          value: '2023',
          label: '2023年',
        },
        {
          value: '2024',
          label: '2024年',
        },
      ],
    }
  },
  created() {},
  mounted() {
    this.getList()
    queryArea({
      districtFlag: 'true',
    }).then((res) => {
      if (res.success) {
        const node = this.findNodeById(res.data, this.$store.getters.user.refId)
        this.cityList = this.removeChildrenAtLevel([node], 1)[0].children
      }
    })
  },
  methods: {
    findNodeById(tree, targetId) {
      // 遍历树中的每个节点
      for (let i = 0; i < tree.length; i++) {
        // 检查当前节点的ID是否为目标ID
        if (tree[i].areaCode === targetId || tree[i].pkid === targetId) {
          // 如果是的话，返回当前节点
          return tree[i]
        }

        // 如果当前节点有子节点，则递归在子节点中查找
        if (tree[i].children && tree[i].children.length > 0) {
          const foundNode = this.findNodeById(tree[i].children, targetId)
          // 如果在子节点中找到了，则返回找到的节点
          if (foundNode !== undefined) {
            return foundNode
          }
        }
      }

      // 如果在树中没有找到目标ID，则返回undefined
      return undefined
    },
    fileDownload(file, fileName = '下载文件', options) {
      // 创建隐藏的可下载链接
      let eleLink = document.createElement('a')
      eleLink.download = fileName
      eleLink.style.display = 'none'
      // 字符内容转变成blob地址
      let blob = options ? new Blob([file], options) : new Blob([file])
      eleLink.href = URL.createObjectURL(blob)
      // 触发点击
      document.body.appendChild(eleLink)
      eleLink.click()
      // 然后移除
      document.body.removeChild(eleLink)
    },
    handleDownloadFile(fileId, fileName) {
      downloadFile(fileId).then((res) => {
        this.fileDownload(res.data, fileName)
      })
    },
    handleRemoveFile(pkid) {
      deleteSubmit(pkid).then((res) => {
        if (res.success) {
          Message.success('删除文件成功！')
          this.getList()
        } else {
          Message.error(res.message)
        }
      })
    },
    handleChangeArea(val) {
      this.page.pageIndex = 1
      if (val.length === 1) {
        this.params.districtId = val[0]
        this.params.areaId = null
      } else {
        this.params.districtId = null
        this.params.areaId = val[val.length - 1]
      }
    },
    getList() {
      querySubmit({ ...this.page, ...this.params }).then((res) => {
        if (res.success) {
          this.tableData = res.data.list
          this.page.total = res.data.total
        }
      })
    },
    getData() {
      queryQuotaList({ ...this.page, ...this.params }).then((res) => {
        if (res.success) {
          this.tableData = res.data.records
          this.page.total = res.data.total
        }
      })
    },
    removeChildrenAtLevel(tree, targetLevel) {
      // 遍历树中的每个节点
      for (let i = 0; i < tree.length; i++) {
        // 检查当前节点的level是否为目标level
        if (tree[i].level === targetLevel) {
          // 如果是的话，移除children属性
          delete tree[i].children
        }

        // 如果当前节点还有子节点，并且子节点的level也为目标level，则递归处理子节点
        if (tree[i].children && tree[i].children.length > 0) {
          this.removeChildrenAtLevel(tree[i].children, targetLevel)
        }
      }

      return tree
    },
    selectFile() {
      return new Promise((resolve) => {
        const fileInput = document.createElement('input')
        fileInput.type = 'file'
        fileInput.accept = '.pdf'
        fileInput.click()
        fileInput.onchange = function (event) {
          const file = event.target.files[0]
          resolve({ message: true, event, file })
        }
      })
    },
    uploadReport(pkid) {
      this.selectFile().then((fileInfo) => {
        const data = new FormData()
        data.append('file', fileInfo.file)
        data.append('type', 'platform')
        uploadFile(data).then((res) => {
          if (res.success) {
            uploadSubmit({
              submitId: pkid,
              attachmentId: res.data,
            }).then((val) => {
              if (val.success) {
                Message.success('上传成功!')
                this.getList()
              } else {
                Message.error(val.message)
              }
            })
          } else {
            Message.error(res.message)
          }
        })
      })
    },
    handleRelease(pkid) {
      releaseIndex(pkid).then((res) => {
        if (res.success) {
          this.$message.success('发布成功！')
          if (this.page.pageIndex === 1) {
            this.getData()
          } else {
            this.page.pageIndex = 1
          }
        }
        // console.log('res :>> ', res);
      })
    },
  },
  watch: {
    page(newVal, oldVal) {
      if (
        !(
          newVal.pageIndex === oldVal.pageIndex &&
          newVal.pageSize === oldVal.pageSize
        )
      ) {
        this.getList()
      }
    },
    params: {
      handler: function () {
        {
          if (this.page.pageIndex === 1) {
            this.getList()
          } else {
            this.page.pageIndex = 1
          }
        }
      },
      deep: true,
    },
  },
}
</script>

<style lang="scss" scoped>
.publish-content {
  width: 100%;
  height: 100%;
  padding: 20px;
  border-radius: 10px;
  box-sizing: border-box;

  .head {
    display: flex;
    justify-content: space-between;
    padding-bottom: 10px;
  }

  .search {
    .el-select {
      margin-right: 10px;
      width: 120px;
    }

    .el-input {
      width: 230px;
    }
  }

  .progress-bg {
    height: 10px;
    border: 1px solid #02bcca;
    border-radius: 5px;

    .progress {
      height: 100%;
      background: #02bcca;
      border-radius: 5px;
    }
  }
  .file-list {
    display: flex;
    flex-direction: column;

    .file-list-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
}
</style>
